#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
                            _ooOoo_  
                           o8888888o  
                           88" . "88  
                          (|  -_-  |)  
                           O\  =  /O  
                        ____/`---'\____  
                      .   ' \\| |// `.  
                       / \\||| : |||// \  
                     / _||||| -:- |||||- \  
                       | | \\\ - /// | |  
                     | \_| ''\---/'' | |  
                      \ .-\__ `-` ___/-. /  
                   ___`. .' /--.--\ `. . __  
                ."" '< `.___\_<|>_/___.' >'"".  
               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
                 \ \ `-. \_ __\ /__ _/ .-` / /  
         ======`-.____`-.___\_____/___.-`____.-'======  
                            `=---='  

         .............................................
                  佛祖镇楼                  BUG辟易
          佛曰:
                  写字楼里写字间，写字间里程序员；
                  程序人员写程序，又拿程序换酒钱。
                  酒醒只在网上坐，酒醉还来网下眠；
                  酒醉酒醒日复日，网上网下年复年。
                  但愿老死电脑间，不愿鞠躬老板前；
                  奔驰宝马贵者趣，公交自行程序员。
                  别人笑我忒疯癫，我笑自己命太贱；
                  不见满街漂亮妹，哪个归得程序员？
'''
# @File  : 3.py
# @Author: huguangzhi
# @Drivce: Thinkpad E470
# @ContactEmail : huguangzhi@ucsdigital.com.com
# @ContactPhone : 13121961510
# @Date  : 2021/9/2 - 16:54
# @Desc  :
# !/usr/bin/env python
# coding:utf-8
import time

from kafka import KafkaProducer


def send_msg_kafka(msg: bytes, topic_name):
    producer.send(topic_name, msg)
    # producer.close()
    print("success")


__author__ = 'ferraborghini'
from socket import socket, AF_INET, SOCK_STREAM
import struct


def bit_ana(bit_str, bit_num):
    res = {}
    if bit_num == 1:
        # byte 1
        if bit_str[:2] == "01":
            res["lift_type"] = "升降梯"
        elif bit_str[:2] == "10":
            res["lift_type"] = "自动扶梯"
        elif bit_str[:2] == "11":
            res["lift_type"] = "自动人行道"

        res["lift_SN"] = int(bit_str[2:], 2) +1

    elif bit_num == 2:
        # byte 2
        if bit_str[:2] == "01":
            res["运行方向"] = "下行"
        elif bit_str[:2] == "10":
            res["运行方向"] = "上行"
        elif bit_str[:2] == "00":
            res["运行方向"] = "无方向（升降梯）"

        res["实际楼层"] = int(bit_str[2:], 2)

    elif bit_num == 3:
        # byte 3
        if bit_str[:2] == "00":
            res["up_down"] = "正常"
        elif bit_str[:2] == "10":
            res["up_down"] = "满载"
        elif bit_str[:2] == "01":
            res["up_down"] = "超载"

        res["check"] = "自动" if bit_str[3] == "0" else "检修"
        res["door"] = "关门" if bit_str[4] == "0" else "开门"
        res["tel_err"] = "无故障" if bit_str[5] == "0" else "有故障"
        res["err"] = "无故障" if bit_str[5] == "0" else "有故障"

    elif bit_num == 4:
        res["消防运行"] = "退出" if bit_str[0] == "0" else "进入"
        res["地震管制"] = "退出" if bit_str[1] == "0" else "进入"
        res["火灾管制"] = "退出" if bit_str[2] == "0" else "进入"
        res["紧急电源"] = "退出" if bit_str[3] == "0" else "进入"
        res["锁梯状态"] = "退出" if bit_str[4] == "0" else "进入"

    elif bit_num == 5:
        res["低速待机"] = "退出" if bit_str[0] == "0" else "进入"

    elif bit_num == 6:
        pass
    elif bit_num == 7:
        pass
    elif bit_num == 8:
        pass
    elif bit_num == 9:
        pass
    elif bit_num == 10:
        tmp = int(bit_str, 2)
        tmp = int("{0:x}".format(tmp))
        if tmp > 30:
            res["high"] = tmp % 30
        else:
            res["high"] = ""

    elif bit_num == 11:
        tmp = int(bit_str, 2)
        tmp = int("{0:x}".format(tmp))
        if tmp > 40:
            res["middel"] = "B"
        elif 40 > tmp > 30:
            res["middel"] = tmp % 30
        else:
            res["middel"] = ""

    elif bit_num == 12:
        tmp = int(bit_str, 2)
        tmp = int("{0:x}".format(tmp))
        if tmp == 47:
            res["low"] = "G"
        elif 40 > tmp >= 30:
            res["low"] = tmp % 30
        elif  tmp== 41:
            res["low"] = "A"
        elif tmp == 42:
            res["low"] = "B"
        else:
            res["low"] = ""

    return res


def desc_lift(byte_str: str):
    # 输入的为一部电梯的信息
    res = {}
    stay_floor = ""
    for num in range(0, len(byte_str), 2):
        # 拿到各个段的16进制数
        byte_num = num // 2 + 1
        state_16 = byte_str[num:num + 2]
        state_10 = int(state_16, 16)  # 转成10进制的
        state_2 = '{:08b}'.format(state_10)  # 转成2进制的
        # print(state_2)
        a = bit_ana(state_2, byte_num)

        res.update(a)
        # print(str(res["高位"]))
    try:
        stay_floor = str(res["high"]) + str(res["middel"]) + str(res["low"])
        try:
            res["stay_floor"] = int(stay_floor)
            if res["stay_floor"] == 0:
                res["stay_floor"] = "G"
        except:
            res["stay_floor"] = stay_floor
    except:
        pass
    return res


def get_all_lift(socket_data):
    res = []
    for item in range(0, len(socket_data[6:-2]), 24):
        res.append(socket_data[6:-2][item: item + 24])

    return res


# 将16进制数据当做字节流传递
def dataSwitch(data):
    str2 = struct.pack('5B',
                       int('00', 16),
                       int('03', 16),
                       int('00', 16),
                       int('40', 16),
                       int('02', 16),
                       )
    return str2


if __name__ == "__main__":

    BUFSIZE = 1024
    ADDR = ('10.171.28.31', 6432)
    tcpCliSock = socket(AF_INET, SOCK_STREAM)
    tcpCliSock.connect(ADDR)
    while True:
        time.sleep(5)
        data = "0004e01b"

        tcpCliSock.send(dataSwitch(data))
        data = tcpCliSock.recv(BUFSIZE)
        if not data:
            break
        print(data.hex())
        # print( struct.unpack("255s255s4I",data))
        #
        # tcpCliSock.close()
        time_info = str(int(time.time() * 1000))
        data = time_info + "--" + data.hex()

        producer = KafkaProducer(bootstrap_servers='192.168.30.114:9092')
        send_msg_kafka(data.encode("utf-8"), 'socket-lift')
        # z_data = []
        for item in get_all_lift(data.split("--")[1]):
            lift_info = desc_lift(str(item))
            # z_data.append(lift_info)
            if str(lift_info["lift_SN"]) == "30":
                z_data = {
                    "当前楼层":lift_info["stay_floor"] ,
                    "电梯编号":lift_info["lift_SN"] ,
                    "运行方向":lift_info["运行方向"],
                    "实际楼层":lift_info["实际楼层"]
                }
                time_info_s = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time_info) / 1000))
                s_data = time_info_s + "--" + str(z_data)
                send_msg_kafka(str(s_data).encode("utf-8"), 'test3')

